from django.http import HttpResponse, FileResponse, JsonResponse
from django.shortcuts import render
import os
import random
from time import sleep
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.middleware.csrf import get_token


# Create your views here.
def showG(request):
    return render(request, 'g.html')


def sendAjax(request):
    return render(request, 'form.html')


def getAjax(request):
    mess = request.GET.get('message')
    # 获取Ajax请求中的参数
    print(mess)
    return HttpResponse('这里是Django,收到!' + str(mess))


def getImg(request):
    pic_url = os.path.join(os.getcwd(), 'static/img.gif')
    music_url = os.path.join(os.getcwd(), 'static/music.mp3')
    # 使用FileResponse来发出response
    return FileResponse(open(music_url, 'rb'))


def getAudioPath(request):
    music_url = 'http://119.23.182.180/azur/t{}.mp3'.format(random.randint(1, 5))
    print('Audio url : {}'.format(music_url))
    return HttpResponse(music_url)


def getAudioSynth(request):
    music_url = 'http://119.23.182.180/azur/t{}.mp3'.format(random.randint(1, 5))
    print('Audio url : {}'.format(music_url))
    sleep(1.5)
    res_obj = {
        'music_url': music_url
    }

    return JsonResponse(res_obj)


@csrf_protect
def get_post(request):
    thisid = request.POST.get('myid')
    return HttpResponse(thisid)

@csrf_exempt
def token(request):
    token = get_token(request)
    res = JsonResponse({'token': token})
    # res.set_cookie('csrftoken', token)
    return res
